/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * CopyDetailUI.java
 *
 * Created on 2010.11.11., 13:09:59
 */
package workshopdesign.UI;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JOptionPane;
import javax.swing.border.TitledBorder;
import org.jdesktop.application.Action;
import workshopdesign.Control.DVDController;
import workshopdesign.Control.LoanController;
import workshopdesign.Model.Copy;
import workshopdesign.Model.DVD;

/**
 *
 * @author Dom
 */
public class CopyDetailUI extends javax.swing.JPanel {

    private enum State {

        Info, Edit, Create
    };
    private BaseUIController parent;
    private Copy copy;
    private DVD dvd;
    private DVDController dvdController = DVDController.getDVDControl();
    private State state = State.Info;
    private LoanController loanController = LoanController.getLoanController();
    private SimpleDateFormat sdf = (SimpleDateFormat) SimpleDateFormat.getInstance();

    /** Creates new form CopyDetailUI */
    public CopyDetailUI(BaseUIController parent, String title, boolean enable_actions) {
        initComponents();

        this.parent = parent;

        this.setBorder(new TitledBorder(title));

        ok_button.setVisible(enable_actions);
        cancel_button.setVisible(enable_actions);

        update_buttons();
    }

    public Copy getCopy() {
        return copy;
    }

    public void setCopy(Copy copy) {
        this.copy = copy;
        dvd = null;
        load_data();
        update_buttons();
    }

    public DVD getDvd() {
        return dvd;
    }

    public void setDvd(DVD dvd) {
        this.dvd = dvd;
        copy = null;

        if (state != State.Create) {
            clear_form();
            state = State.Create;
        }
        update_buttons();
    }

    public void load_data() {
        if (copy == null) {
            clear_form();
            return;
        }

        sdf.applyPattern("yyyy.MM.dd.");

        date_field.setText(sdf.format(copy.getPurchaseDate()));
        price_field.setText(String.valueOf(copy.getPurchasePrice()));

        if (loanController.is_copy_available(copy)) {
            state_label.setText("Available");
        } else {
            state_label.setText("Rented out");
        }
    }

    private void save_data() {
        try {
            sdf.applyPattern("yyyy.MM.dd.");
            Date date = sdf.parse(date_field.getText());
            Long price = Long.parseLong(price_field.getText());
            copy.setPurchaseDate(date);
            copy.setPurchasePrice(price);

            parent.update_data();
        } catch (ParseException ex) {
            JOptionPane.showMessageDialog(
                    this,
                    "Error: The entered values are in incorrect format.\n" +
                    "Please make sure the date uses following pattern:\n'" +
                    "yyyy.MM.dd.'",
                    "Error parsing data!",
                    JOptionPane.ERROR_MESSAGE);
        }
    }

    private void delete_copy(){

        int answer = JOptionPane.showConfirmDialog(
                this,
                "Do you really want to delete this Copy? ID = " +
                String.valueOf(copy.getId()) +
                "\nAll the associated loans will be deleted also",
                "Delete Copy",
                JOptionPane.YES_NO_OPTION);

        if (answer != JOptionPane.YES_OPTION) {
            return;
        }

        loanController.deleteLoansByCopy(copy.getId());

        dvdController.remove_copy(copy.getId());

        clear_form();
        parent.update_data();
        parent.clear_selection();
    }

    private void clear_form() {
        date_field.setText("");
        price_field.setText("");
        state_label.setText("");
    }

    private void update_buttons() {
        switch (state) {
            case Create:
                ok_button.setText("Add");
                cancel_button.setText("Clear");
                break;
            case Edit:
                ok_button.setText("Save");
                cancel_button.setText("Cancel");
                break;
            case Info:
                ok_button.setText("Edit");
                cancel_button.setText("Delete");
                break;
        }
        boolean editable = ((dvd != null) || (copy != null)) && ok_button.isVisible();

        ok_button.setEnabled(editable);
        cancel_button.setEnabled(editable);
        
        date_field.setEditable(editable);
        price_field.setEditable(editable);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        date_field = new javax.swing.JTextField();
        price_field = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        ok_button = new javax.swing.JButton();
        cancel_button = new javax.swing.JButton();
        state_label = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(workshopdesign.WorkshopDesignApp.class).getContext().getResourceMap(CopyDetailUI.class);
        setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("Form.border.title"))); // NOI18N
        setName("Form"); // NOI18N

        date_field.setEditable(false);
        date_field.setText(resourceMap.getString("date_field.text")); // NOI18N
        date_field.setName("date_field"); // NOI18N

        price_field.setEditable(false);
        price_field.setText(resourceMap.getString("price_field.text")); // NOI18N
        price_field.setName("price_field"); // NOI18N

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(workshopdesign.WorkshopDesignApp.class).getContext().getActionMap(CopyDetailUI.class, this);
        ok_button.setAction(actionMap.get("ok_action")); // NOI18N
        ok_button.setText(resourceMap.getString("ok_button.text")); // NOI18N
        ok_button.setName("ok_button"); // NOI18N

        cancel_button.setAction(actionMap.get("cancel_action")); // NOI18N
        cancel_button.setText(resourceMap.getString("cancel_button.text")); // NOI18N
        cancel_button.setName("cancel_button"); // NOI18N

        state_label.setText(resourceMap.getString("state_label.text")); // NOI18N
        state_label.setName("state_label"); // NOI18N

        jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N
        jLabel4.setName("jLabel4"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(ok_button)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 122, Short.MAX_VALUE)
                .addComponent(cancel_button))
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addComponent(jLabel2)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(state_label, javax.swing.GroupLayout.DEFAULT_SIZE, 169, Short.MAX_VALUE)
                    .addComponent(price_field, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 169, Short.MAX_VALUE)
                    .addComponent(date_field, javax.swing.GroupLayout.DEFAULT_SIZE, 169, Short.MAX_VALUE)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE, false)
                    .addComponent(date_field, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE, false)
                    .addComponent(price_field, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(state_label, javax.swing.GroupLayout.PREFERRED_SIZE, 13, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 17, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(ok_button)
                    .addComponent(cancel_button)))
        );
    }// </editor-fold>//GEN-END:initComponents

    @Action
    public void ok_action() {
        switch (state) {
            case Create:
                if (dvd == null) {
                    return;
                }
                try {
                    sdf.applyPattern("yyyy.MM.dd.");
                    Date date = sdf.parse(date_field.getText());
                    Long price = Long.parseLong(price_field.getText());
                    dvdController.add_copy(date, price, dvd.getId());
                    clear_form();
                } catch (Exception e) {
                }
                break;
            case Edit:
                save_data();
                load_data();
                state = State.Info;
                update_buttons();
                break;
            case Info:
                state = State.Edit;
                update_buttons();
                break;
        }
    }

    @Action
    public void cancel_action() {
        switch (state) {
            case Create:
                clear_form();
                break;
            case Edit:
                load_data();
                state = State.Info;
                update_buttons();
                break;
            case Info:
                delete_copy();
                break;
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancel_button;
    private javax.swing.JTextField date_field;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JButton ok_button;
    private javax.swing.JTextField price_field;
    private javax.swing.JLabel state_label;
    // End of variables declaration//GEN-END:variables
}
